//
//  BaseViewController.m
//  XXCarPassenger
//
//  Created by Mickey on 2017/1/22.
//  Copyright © 2017年 711. All rights reserved.
//

#import "BaseViewController.h"


#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
@interface BaseViewController ()

@property (nonatomic, assign) UIStatusBarStyle statusBarStyle;
@property (nonatomic, assign) BOOL statusBarHidden;
@property (nonatomic, assign) BOOL changeStatusBarAnimated;
@end

@implementation BaseViewController

-(instancetype) init{
    self = [ super init ];
    if (self) {
        self.titleviewIsButton = YES ;
    }
    return self ;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBackBtn ] ;
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
}


- (void)setTitle:(NSString *)title{
    if (self.titleviewIsButton) {
        UIButton *titleBtn = [ UIButton buttonWithType:UIButtonTypeCustom ] ;
        titleBtn.titleLabel.font = [ UIFont systemFontOfSize:17 ] ;
        titleBtn.userInteractionEnabled = NO ;
        titleBtn.frame = CGRectMake(0, 5, SCREEN_WIDTH-160, 34) ;
        self.navigationItem.titleView = titleBtn ;
        NSMutableAttributedString *attrStr = [[ NSMutableAttributedString alloc ] initWithString:[ NSString stringWithFormat:@" %@%@",title ? @"":@"",title ?title : @""] ];
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attrStr.length)];
        UIImage *icon = [UIImage imageNamed:@"icon_map_middle_car"];
        NSTextAttachment *attacgment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
        attacgment.image = icon;
        CGFloat imageSzie = titleBtn.titleLabel.font.lineHeight * 1.2;
        attacgment.bounds = CGRectMake(0, -imageSzie * 0.2 , imageSzie, imageSzie);
        [attrStr insertAttributedString:[NSAttributedString attributedStringWithAttachment:attacgment] atIndex:0];
        [titleBtn setAttributedTitle:attrStr forState:UIControlStateNormal];
    }
}

//一般默认为返回按钮只要图标不要字
- (void)setBackBarItemWithImg:(UIImage *)img{
    self.navigationItem.leftBarButtonItem = [[ UIBarButtonItem alloc ] initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(backBarBtnClicked:)];
}

- (void)setBackItemWithTitle:(NSString *)title{
    self.navigationItem.leftBarButtonItem = [[ UIBarButtonItem alloc ] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(backBarBtnClicked:)];
}


/**
 可以为字或者图片
 
 @param rights rightItems的标题或图片数组 可以混合
 UI肯定会不好看  可自己转initWithCustomView
 */
- (void)setRightItemWithRights:(NSArray *)rights{
    NSMutableArray *items = [ NSMutableArray arrayWithCapacity:rights.count ] ;
    for ( int i = 0;  i < rights.count ; i++ ) {
        UIBarButtonItem *item = nil  ;
        if ([rights[i] isKindOfClass:[UIImage class]]) {
            item = [[ UIBarButtonItem alloc ] initWithImage:(UIImage *)rights[i] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarItemClicked:)] ;
            item.tag = i +2000 ;
        }else if ([rights[i] isKindOfClass:[NSString class]]){
            item = [[ UIBarButtonItem alloc ] initWithTitle:(NSString *)rights[i] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarItemClicked:)];
            item.tag = i+ 2000 ;
        }else{
            continue ;
        }
        [items addObject:item ];
    }
    self.navigationItem.rightBarButtonItems = items ;
}

- (IBAction)rightBarItemClicked:(id)sender{
    NSLog(@"%@",sender);
}


- (IBAction)backBarBtnClicked:(id)sender{
    
}

/**
  
 UINavigationBar默认有个shadow 如果不去除的话 导航栏地下会有黑线 
 有很多公司的产品要求去除黑线 故封此方法
 
 @param hidden hidden为YES的时候 黑线隐藏 ; 为NO的时候显示
 
 一般在viewWillAppear里设置yes  viewWillDisappear里设置NO
 */
- (void)setNavgationBarLineHidden:(BOOL)hidden {
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        if (hidden) {
            [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault ];
            [self.navigationController.navigationBar setShadowImage:[UIImage new] ];
        }else{
            [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
            [self.navigationController.navigationBar setShadowImage:nil];
        }
    }
}

#pragma mark -- StatusBar
-(UIStatusBarStyle )preferredStatusBarStyle{
    if (self.statusBarStyle) {
        return self.statusBarStyle ;
    }else{
        return UIStatusBarStyleLightContent ;
    }
}

-(BOOL)prefersStatusBarHidden{
    return self.statusBarHidden ;
}
/**
 * 功能：设置修改StatusBar
 * 参数：（1）StatusBar样式：statusBarStyle
 *      （2）是否隐藏StatusBar：statusBarHidden
 *      （3）是否动画过渡：animated
 */
- (void)changeStatusBarStyle:(UIStatusBarStyle)statusBarStyle
             statusBarHidden:(BOOL)statusBarHidden
     changeStatusBarAnimated:(BOOL)animated {
    
    self.statusBarStyle=statusBarStyle;
    self.statusBarHidden=statusBarHidden;
    if (animated) {
        [UIView animateWithDuration:0.25 animations:^{
            [self setNeedsStatusBarAppearanceUpdate];
        }];
    }
    else{
        [self setNeedsStatusBarAppearanceUpdate];
    }
}
/**
 * 功能：隐藏显示导航栏
 * 参数：（1）是否隐藏导航栏：isHide
 *      （2）是否有动画过渡：animated
 */
- (void)hideNavigationBar:(BOOL)isHide
                 animated:(BOOL)animated{
    
    if (animated) {
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBarHidden=isHide;
        }];
    }
    else{
        self.navigationController.navigationBarHidden=isHide;
    }
}


- (void)setIsExtendLayout:(BOOL)isExtendLayout {
    
    if (!isExtendLayout) {
        [self initializeSelfVCSetting];
    }
}

- (void)initializeSelfVCSetting {
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
}



#pragma mark - 屏幕旋转
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate {
    
    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    
    return UIInterfaceOrientationPortrait;
}

#pragma mark - 屏幕旋转则在子类中调用以下代码 ⚠️⚠️⚠️
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//
//    return UIInterfaceOrientationMaskAll ;
//}
//
//- (BOOL)shouldAutorotate {
//
//    return YES;
//}
//
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
//
//    return UIInterfaceOrientationPortrait | UIInterfaceOrientationPortraitUpsideDown|UIInterfaceOrientationLandscapeLeft|UIInterfaceOrientationLandscapeRight;
//}



//去除返回多余的字 如果需要 就在viewDidLoad中设置 [self setBackBtn ];
-(void)setBackBtn{
    //返回按钮的标题会带有上级的title可以这样去掉
    NSArray *viewControllerArray = [self.navigationController viewControllers ];
    if ([viewControllerArray containsObject:self]) {
        int preViewControllerIndex = (int)[ viewControllerArray indexOfObject:self] -1 ;
        UIViewController *previous ;
        if (preViewControllerIndex > 0) {
            previous = [ viewControllerArray objectAtIndex:preViewControllerIndex];
            previous.navigationItem.backBarButtonItem  = [[ UIBarButtonItem alloc ] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
        }
    } 
}


@end
